package com.lsh.netty.simple;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;

/**
 * @author ：LiuShihao
 * @date ：Created in 2020/9/21 4:46 下午
 * @desc ：
 */
public class NettyServer {
    public static void main(String[] args) throws InterruptedException {
        //创建BossGroup 和 WorkerGroup
        //创建两个线程组
        //BossGroup只处理连接请求，真正的和客户端业务处理，会交给workerGroup处理  两个都是无限循环
        NioEventLoopGroup bossGroup = new NioEventLoopGroup();
        NioEventLoopGroup workerGroup = new NioEventLoopGroup();
        //创建服务器端的启动对象，配置参数
        try {
        ServerBootstrap serverBootstrap = new ServerBootstrap();
        serverBootstrap.group(bossGroup, workerGroup)
                .channel(NioServerSocketChannel.class)//使用NioSocketChannel作为服务器的通道实现
                .option(ChannelOption.SO_BACKLOG, 128)//设置线程队列得到连接个数
                .childOption(ChannelOption.SO_KEEPALIVE, true)//设置保持活动连接的状态
                .childHandler(new ChannelInitializer<SocketChannel>() {
                    protected void initChannel(SocketChannel ch) throws Exception {//创建一个通道测试对象 匿名对象
                        ch.pipeline().addLast(new NettyServerHandler());//给pipeline设置处理器
                    }
                });//给workerGroup 的EventLoop 对应的g管道设置处理器

        System.out.println("服务器 is Ok~");
        ChannelFuture cf = serverBootstrap.bind(6666).sync();//绑定一个端口并且同步处理
            cf.addListener(new ChannelFutureListener() {
                @Override
                public void operationComplete(ChannelFuture channelFuture) throws Exception {
                    if(cf.isSuccess()){
                        System.out.println("监听端口6666成功");
                    }else {
                        System.out.println("监听端口6666失败");
                    }
                }
            });
        //对 关闭通道  进行监听
        cf.channel().closeFuture().sync();
        }finally {
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }
}
//最灿烂的烟火总是先坠落